package com.yidu.servlet.fileuploaddemo;

import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "FileUploadServlet", value = "/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SmartUpload smartUpload=new SmartUpload();
        //this指的是当前类的对象，此处FileUploadServlet
        smartUpload.initialize(this.getServletConfig(),request,response);
        try {
            smartUpload.upload();
        } catch (SmartUploadException e) {
            throw new RuntimeException(e);
        }
        //获取所有的上传的文件
        Files files = smartUpload.getFiles();
        System.out.println(files.getCount());
        //files.getFile(0) 获取上传的第一个文件  .getFileName()获取上传文件的名字
        String fileName=files.getFile(0).getFileName();
        //解决上传文件名字符乱码问题iso-8859-1国际编码英文编码，
        fileName=new String(fileName.getBytes("gbk"),"utf-8");
        System.out.println(fileName);
        //request.getRealPath("/") 获得工程部署后的物理路径 （D盘，C盘）
        System.out.println(request.getRealPath("/"));;
        try {
            files.getFile(0).saveAs("d:\\"+fileName);
            //由于使用了SmartUpload包，将原来的请求封装成Request，
            Request req = smartUpload.getRequest();
            //因此原来的request请求对象不能使用，需要使用SmartUpload中的请求
            //并且原来request中的方法同样适用于SmartUpload中的请求
            String uname=req.getParameter("uname");

            uname=new String(uname.getBytes("gbk"),"utf-8");
            System.out.println(uname);
            //saveAs("保存文件的路径") 保存上传的文件
//            files.getFile(0).saveAs(request.getRealPath("/")+fileName);
        } catch (SmartUploadException e) {
            throw new RuntimeException(e);
        }

    }
}
